package com.ys.controller.api.sys;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.entity.flow.YspTaskAuditUser;
import com.ys.util.admin.ConditionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.entity.flow.YspDef;
import com.ys.entity.flow.YspDeploy;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.flow.YspTaskAuditUserEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/ysProcInst")
public class ApiInterYsProcInstController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<YsProcInst> commonApiService;

//	@RequiresPermissions("ysProcInst:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute YsProcInst cond,String conditions,
			Integer stateAll // 0待处理1已处理2已完成3制单中
			){
		
		String loginUserId = ShiroUtils.getUserId();
		
		cond.setStatus(1);
		cond.setOrderby("A.CreateTime desc");
		
		cond.addLeftJoin("YSP_Def B on B.Id = A.DefId")
			.addField("B.Name defName");

		cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.CreateUserId")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName");//制单人

		cond.addLeftJoin("YS_ProcInstOther C on C.Bid = A.Bid")
				.addField("C.Remark remark");
		
		if (stateAll != null) {
			if (stateAll == 0) {
				cond.setStateFlow(YsProcInstEnum.StateFlow.PROCESS.value);
				if ("admin".equals(loginUserId)) {
					cond.where("A.TaskId in (select TaskId from YSP_TaskAuditUser where State = " + YspTaskAuditUserEnum.State.FOR_AUDIT.value + ")");
				} else {
					cond.where("A.TaskId in (select TaskId from YSP_TaskAuditUser where UserId = '" + loginUserId + "' and State = " + YspTaskAuditUserEnum.State.FOR_AUDIT.value + ")");
				}
			} else if (stateAll == 1) {
				cond.where("A.StateFlow != " + YsProcInstEnum.StateFlow.FINISH.value);
				if ("admin".equals(loginUserId)) {
					cond.where("A.TaskId in (select TaskId from YSP_TaskAuditUser where State = " + YspTaskAuditUserEnum.State.SUCCESS.value + ")");
				} else {
					cond.where("A.TaskId in (select TaskId from YSP_TaskAuditUser where UserId = '" + loginUserId + "' and State in (" + YspTaskAuditUserEnum.State.FAILED.value + "," + YspTaskAuditUserEnum.State.SUCCESS.value + "))");
				}
			} else if (stateAll == 2) {
				cond.setStateFlow(YsProcInstEnum.StateFlow.FINISH.value);
				if ("admin".equals(loginUserId)) {
				} else {
					cond.where("A.TaskId in (select TaskId from YSP_TaskAuditUser where UserId = '" + loginUserId + "')");
				}
			} else if (stateAll == 3) {
				cond.setStateFlow(YsProcInstEnum.StateFlow.INIT.value);
				if ("admin".equals(loginUserId)) {
				} else {
					cond.where("A.CreateUserId = '" + loginUserId + "'");
				}
			}
		}

		cond.addLeftJoin("(SELECT MAX(D.Id) AS Id,D.TaskId FROM YSP_TaskAuditUser D WHERE D.State!=0 GROUP BY D.TaskId) E ON E.TaskId = A.TaskId")
				.addLeftJoin("YSP_TaskAuditUser F ON F.Id = E.Id")
				.addField("CASE WHEN F.State=2 THEN '审批中（退回）' " +
                        "WHEN (F.State!=2 OR  F.State IS NULL) AND A.StateFlow = 0 THEN '制单' " +
                        "WHEN F.State!=2 AND A.StateFlow = 1 THEN '审批中' " +
                        "WHEN F.State!=2 AND A.StateFlow = 2 THEN '已完成' " +
                        "WHEN F.State!=2 AND A.StateFlow = 3 THEN '已删除' " +
                        "ELSE '审批单据不存在' END _ys_stateFlow");




		//查询条件
		String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
		if (nameLinked != null){
			cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
		}

		LayuiTableVoJA setList = commonApiService.searchLay(cond);
		return setList;
	}


	/**
	 * 获取菜单ID（通过BID）
	 */
	@PostMapping("/getMenuIdByBid")
    @ResponseBody
	public R getMenuIdByBid(Model model, HttpServletRequest request, HttpServletResponse response,
			String bid){
		
		if (bid == null || bid.length() == 0) {
			return R.error("单号不能为空");
		}
		
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		YspDef yspDef = new YspDef().setId(ysProcInst.getDefId()).queryFirst();
		YspDeploy yspDeploy = new YspDeploy().setId(yspDef.getDeployId()).queryFirst();
		YsMenu ysMenu = new YsMenu().setFlowModelId(yspDeploy.getModelId()).queryFirst();
		
		return R.ok(ysMenu.getId());
	}
	
	/**
	 * 加载数据
	 */
	@PostMapping("/index")
    @ResponseBody
	public R index(Model model, HttpServletRequest request, HttpServletResponse response){
		
		
		return R.ok();
	}
}
